/**
 * 全局认证服务
 * 参考card.vue的成功实现方式
 */

class AuthService {
  constructor() {
    this.isInitialized = false
    this.initPromise = null
    this.retryCount = 0
    this.maxRetries = 3
  }

  /**
   * 初始化认证服务
   * @returns {Promise}
   */
  async init() {
    if (this.isInitialized) {
      return Promise.resolve()
    }

    if (this.initPromise) {
      return this.initPromise
    }

    this.initPromise = this._doInit()
    return this.initPromise
  }

  /**
   * 执行初始化 - 参考card.vue的getOpenId方法
   * @private
   */
  async _doInit() {
    try {
      console.log('开始认证服务初始化...')
      
      // 获取openId - 直接使用card.vue的成功逻辑
      await this.getOpenId()
      
      this.isInitialized = true
      console.log('认证服务初始化完成')
    } catch (error) {
      console.error('认证服务初始化失败:', error)
      // 不抛出错误，允许部分初始化
      this.isInitialized = true
    }
  }

  /**
   * 获取openId - 完全参考card.vue的实现
   * @returns {Promise<string>}
   */
  async getOpenId() {
    return new Promise((resolve, reject) => {
      console.log('=== 开始获取OpenId ===')
      
      // 获取本地缓存中的 openId
      let data = uni.getStorageSync('openId')
      if (data && data.openid) {
        console.log('从本地存储获取OpenId:', data.openid)
        this.openId = data.openid
        
        // 使用获取到的openId 去后台查询个人信息
        this.queryCurrentUserInfoByOpenId().then(() => {
          this.querySupplyDefault().then(() => {
            resolve(data.openid)
          })
        })
      } else {
        console.log('本地没有OpenId，开始微信登录...')
        uni.login({
          provider: 'weixin',
          onlyAuthorize: true,
          success: async (loginRes) => {
            let code = loginRes.code
            let payload = { code }
            
            try {
              const app = getApp()
              if (!app || !app.$api) {
                this.retryCount++
                console.log(`App not ready, retrying... (${this.retryCount}/${this.maxRetries})`)
                
                if (this.retryCount >= this.maxRetries) {
                  console.error('App始终未准备好，停止重试')
                  reject(new Error('App未准备好，无法获取OpenId'))
                  return
                }
                
                setTimeout(() => {
                  this.getOpenId().then(resolve).catch(reject)
                }, 2000)
                return
              }
              
              let res = await app.$api.getOpenIdByCode(payload);
              if (res && res.openid) {
                console.log('微信登录获取OpenId成功:', res.openid)
                this.openId = res.openid
                
                // 更新store
                if (app.$store) {
                  app.$store.commit('setOpenId', res)
                }
                
                // 使用获取到的openId 去后台查询个人信息
                await this.queryCurrentUserInfoByOpenId()
                await this.querySupplyDefault()
                
                resolve(res.openid)
              } else {
                console.error('获取OpenId失败:', res)
                reject(new Error('获取OpenId失败'))
              }
            } catch (error) {
              console.error('微信登录失败:', error)
              reject(error)
            }
          },
          fail: (error) => {
            console.error('微信登录失败:', error)
            reject(error)
          }
        });
      }
    })
  }

  /**
   * 通过openId查询用户信息 - 参考card.vue的实现
   * @returns {Promise<Object>}
   */
  async queryCurrentUserInfoByOpenId() {
    try {
      if (!this.openId) {
        console.log('没有openId，跳过用户信息查询')
        return null
      }

      const app = getApp()
      if (!app || !app.$api) {
        console.log('App not ready, skipping user info query')
        return null
      }

      console.log('开始查询用户信息，openId:', this.openId)
      let res = await app.$api.queryCurrentCardByOpenId({
        openId: this.openId
      })

      if (res.success && res.result) {
        console.log('=== 获取用户信息成功 ===')
        console.log('用户信息详情:', JSON.stringify(res.result, null, 2))
        console.log('用户ID:', res.result.id)
        console.log('用户昵称:', res.result.nickname || res.result.name)
        console.log('用户头像:', res.result.avatar || res.result.headImg)
        console.log('OpenId:', res.result.openId)
        console.log('========================')
        
        // 更新store
        if (app.$store) {
          app.$store.commit('userInfo', res.result)
          app.$store.commit('setIsSelf', true)
          console.log('用户信息已更新到Store')
        }
        
        return res.result
      } else {
        console.log('用户信息不存在，可能需要创建名片')
        console.log('API响应:', res)
        return null
      }
    } catch (error) {
      console.error('查询用户信息失败:', error)
      return null
    }
  }

  /**
   * 获取供应商信息 - 参考card.vue的实现
   * @returns {Promise<Object>}
   */
  async querySupplyDefault() {
    try {
      if (!this.openId) {
        console.log('没有openId，跳过供应商信息查询')
        return null
      }

      const app = getApp()
      if (!app || !app.$api) {
        console.log('App not ready, skipping supplier info query')
        return null
      }

      console.log('开始查询供应商信息，openId:', this.openId)
      let res = await app.$api.querySupplyDefault({
        openId: this.openId
      })

      if (res.success) {
        console.log('=== 获取供应商信息成功 ===')
        console.log('供应商信息详情:', JSON.stringify(res.result, null, 2))
        console.log('供应商ID:', res.result.id)
        console.log('供应商名称:', res.result.name || res.result.companyName)
        console.log('========================')
        
        // 更新store
        if (app.$store) {
          app.$store.commit('setSupplierInfo', res.result)
          console.log('供应商信息已更新到Store')
        }
        
        return res.result
      }
      return null
    } catch (error) {
      console.error('获取供应商信息失败:', error)
      return null
    }
  }

  /**
   * 检查用户是否已登录
   * @returns {boolean}
   */
  isLoggedIn() {
    try {
      const app = getApp()
      if (!app || !app.$store) {
        // 如果store不可用，检查本地存储
        const localOpenId = uni.getStorageSync('openId')
        const localUserInfo = uni.getStorageSync('_userInfo')
        return !!(localOpenId && localUserInfo)
      }
      
      const openId = app.$store.getters.openId
      const userInfo = app.$store.getters.userInfo
      return !!(openId && userInfo)
    } catch (error) {
      console.log('Store not ready, checking local storage')
      const localOpenId = uni.getStorageSync('openId')
      const localUserInfo = uni.getStorageSync('_userInfo')
      return !!(localOpenId && localUserInfo)
    }
  }

  /**
   * 检查用户是否有名片
   * @returns {boolean}
   */
  hasCard() {
    try {
      const app = getApp()
      if (!app || !app.$store) {
        // 如果store不可用，检查本地存储
        const localUserInfo = uni.getStorageSync('_userInfo')
        return !!(localUserInfo && localUserInfo.id)
      }
      
      const userInfo = app.$store.getters.userInfo
      return !!(userInfo && userInfo.id)
    } catch (error) {
      console.log('Store not ready, checking local storage')
      const localUserInfo = uni.getStorageSync('_userInfo')
      return !!(localUserInfo && localUserInfo.id)
    }
  }

  /**
   * 获取当前用户信息
   * @returns {Object}
   */
  getCurrentUser() {
    try {
      const app = getApp()
      if (!app || !app.$store) {
        // 如果store不可用，从本地存储获取
        return uni.getStorageSync('_userInfo')
      }
      
      return app.$store.getters.userInfo
    } catch (error) {
      console.log('Store not ready, using local storage')
      return uni.getStorageSync('_userInfo')
    }
  }

  /**
   * 获取当前openId
   * @returns {string}
   */
  getCurrentOpenId() {
    try {
      const app = getApp()
      if (!app || !app.$store) {
        // 如果store不可用，从本地存储获取
        const localOpenId = uni.getStorageSync('openId')
        return localOpenId ? localOpenId.openid : ''
      }
      
      return app.$store.getters.openId
    } catch (error) {
      console.log('Store not ready, using local storage')
      const localOpenId = uni.getStorageSync('openId')
      return localOpenId ? localOpenId.openid : ''
    }
  }

  /**
   * 确保用户已登录
   * @returns {Promise<boolean>}
   */
  async ensureLogin() {
    try {
      if (!this.isLoggedIn()) {
        console.log('用户未登录，开始登录流程...')
        await this.init()
      }
      return this.isLoggedIn()
    } catch (error) {
      console.error('确保登录失败:', error)
      return false
    }
  }

  /**
   * 重置认证状态
   */
  reset() {
    this.isInitialized = false
    this.initPromise = null
    this.openId = null
    this.retryCount = 0
  }
}

// 创建单例实例
const authService = new AuthService()

export default authService
